package com.milepost.messagepush.filter;

import com.alibaba.fastjson.JSONObject;
import com.milepost.messagepush.common.constant.MilepostConstant;
import com.milepost.messagepush.response.Response;
import com.milepost.messagepush.response.ResponseHelper;
import com.milepost.workflow.user.entity.UsersEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;

import javax.servlet.FilterConfig;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.List;

/**
 * @author huarf
 * @Description 拦截除登录意外的所有请求，
 * 判断session中是否有用户信息，
 * 有则放行，
 * 没有则返回json数据
 * @create 2022-04-01 17:02
 */
@Slf4j
public class SessionFilter implements Filter {

    private static List<String> notFilterResList = Arrays.asList("/user/login", "/user/logout");

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        try {

            String servletPath = request.getServletPath();
            //登录登出接口，还可以指定其他的接口              静态资源
            if (notFilterResList.contains(servletPath) || servletPath.startsWith("/admin/")) {
                //放行
                filterChain.doFilter(request, response);
            } else {

                HttpSession session = request.getSession();

                UsersEntity userEntity = (UsersEntity) session.getAttribute(MilepostConstant.USER_SESSION_KEY);

                if (userEntity != null) {
                    filterChain.doFilter(request, response);
                } else {
                    log.warn("SessionFilter拦截到未登录用户");
                    response.setStatus(HttpStatus.UNAUTHORIZED.value());
                    Response<String> failResponse = ResponseHelper.createFailResponse();
                    failResponse.setMsg("登录超时，请重新登录");
                    writeToResponse(response, failResponse);
                }
            }

        } catch (Exception e) {
            log.error("SessionFilter异常", e);
            response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
            Response<String> exceptionResponse = ResponseHelper.createExceptionResponse(e);
            writeToResponse(response, exceptionResponse);
        }
    }

    @Override
    public void destroy() {

    }

    /**
     * 将 Response 对象写入到 response 中
     *
     * @param servletResponse
     * @param response
     * @throws IOException
     */
    protected void writeToResponse(ServletResponse servletResponse, Response<String> response) throws IOException {

        HttpServletResponse res = (HttpServletResponse) servletResponse;
        //设置Content-Type
        res.setContentType("application/json;charset=UTF-8");
        //设置charset
        res.setCharacterEncoding("UTF-8");
        //写入
        PrintWriter writer = res.getWriter();
        writer.write(JSONObject.toJSONString(response));
    }

}
